<template>
  <div class="wrap">
    <div class="content">
      <div class="video-wrap" id="video-wrap">
        <div
          class="video-item"
          v-for="(item, index) in result"
          :key="index"
          :id="`video-item${index + 1}`"
          :class="[
            videoSelectedIndex === index ? 'activeVideo' : '',
            'video-item' + girdActiveIndex,
          ]"
          v-if="girdActiveIndex > index"
          @click="clickVideoItem(index)"
        >
          <!-- 
            :data="{
              stream:
                'ws://52.131.47.150:48000/live/000.flv?tik=441aa579164f7dd5aec3c6e4c47a3371&tikpwd=',
            }"
         -->
          <Video
            class="hhh"
            v-if="item.stream != ''"
            ref="myvideo"
            :data="item"
            :activeIndex="activeIndex"
            :index="index"
          />
        </div>
      </div>
      <div class="grid-wrap">
        <ul>
          <li
            class="grid-li"
            v-for="(item, index) in girdArr"
            :key="index"
            :class="{ activeGrid: girdActiveIndex === item.id }"
            @click="clickGird(item.id, index)"
          >
            <img class="top" :src="item.icon" />
          </li>
        </ul>
        <div class="task_name">任务名称：{{ task_name }}</div>
        <!-- <div class="task_name">播放设备：{{ this.resultArr.length }}个</div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { getData, postData } from "@/request/http";
import bus from "@/utils/bus";
import Video from "./VideoAuto.vue";
export default {
  name: "VideoWrap",
  components: { Video },
  props: {},
  data() {
    return {
      videoSrc: "",
      dataArr: [],
      videoSelectedIndex: 0,
      selectIndex: 0,
      activeIndex: 0,
      //底部布局 index
      girdActiveIndex: 9,
      girdArr: [
        { id: 1, icon: require("@/assets/img/screen-ico-01.png") },
        { id: 4, icon: require("@/assets/img/screen-ico-04.png") },
        { id: 9, icon: require("@/assets/img/screen-ico-09.png") },
        { id: 16, icon: require("@/assets/img/screen-ico-16.png") },
      ],
      clickVideoScreenArr: [], //点击的video的id的数组
      datas: {}, // 数据给video传name
      task_id: "",
      task_name: "",
      loop_interval: 0,
      count: 0,
      data: [], // 初始化数据
      resultArr: [], // videourl数组
      ajaxVideoArr: [], // 请求数组
      result: [],
      timer: null,
    };
  },
  created() {},
  computed: {},
  async mounted() {
    this.task_id = this.$route.query.task_id;
    this.task_name = this.$route.query.task_name;
    this.loop_interval = this.$route.query.loop_interval;
    this.$message.success("请先选择分屏！");
  },
  methods: {
    /*
        请求控制
    */
    async ajaxAll(ajaxArr) {
      // console.log(ajaxArr);

      this.resultArr = [];
      if (Array.isArray(ajaxArr) && ajaxArr.length > 0) {
        let result = "";
        try {
          for (let i = 0; i < ajaxArr.length; i++) {
            result = await ajaxArr[i]["fn"];
            this.resultArr.push({
              stream: result.datas.stream,
              ...ajaxArr[i]["data"],
              _index: ajaxArr[i]["_index"],
            });
          }
          //  console.log(this.resultArr);
        } catch (err) {
          this.resultArr.push({
            stream: "",
            ...ajaxArr[i]["data"],
            _index: ajaxArr[i]["_index"],
          });
        }
        this.result = JSON.parse(JSON.stringify(this.resultArr));
        // console.log(this.result);
        await this.fnInterval();
      }
    },

    /*
        请求video url
    */
    getUrl(sn, chns) {
      if (!sn) {
        return;
      }
      return new Promise((resolve, reject) => {
        postData("/adminweb/device/stream/live/url/ticket/lasted/unlimited", {
          sn: sn,
          ptl: "WS-FLV",
          channel: chns ? chns : 0,
          sub: 0,
        })
          .then((res) => {
            if (res.code == 0) {
              resolve(res);
            }
          })
          .catch((res) => {
            reject("error");
          });
      });
    },

    /*
        初始化
    */
    async init() {
      postData("/adminweb/video/live/playing/looptask/device/list", {
        task_id: this.task_id,
      })
        .then((res) => {
          if (res.code == 0) {
            this.data = res.datas.devices;
            // console.log(res.datas.devices);
            this.getAllUrl(res.datas.devices);
          } else if (res.code == -56055) {
            return;
          } else {
            this.$message.error(res.code + "，" + res.msg);
          }
        })
        .catch((res) => {
          this.$message.error("加载失败");
        });
    },

    /*
        创建ajax请求数组
    */
    async getAllUrl(data) {
      this.ajaxVideoArr = [];
      if (Array.isArray(data) && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          // console.log(item.channel);
          this.ajaxVideoArr.push({
            fn: this.getUrl(item.sn, item.channel),
            data: item,
            _index: i + 1,
          });
        }
        this.ajaxAll(this.ajaxVideoArr);
      }
    },

    /*
        自动轮询
    */
    async fnInterval() {
      let loop_interval = this.loop_interval * 1000;
      //  console.log(loop_interval);
      let arr = JSON.parse(JSON.stringify(this.resultArr));
      let start = 0;
      let end = this.girdActiveIndex;
      let allEnd = parseInt(arr.length / this.girdActiveIndex);
      this.result = arr.slice(0, this.girdActiveIndex);
      if (Array.isArray(arr) && arr.length > 0) {
        this.timer = setInterval(() => {
          this.count++;
          this.$message.success("即将播放下一组");
          setTimeout(() => {
            if (this.count > allEnd) {
              this.count = 0;
              start = 0;
              this.result = arr.slice(start, this.girdActiveIndex);
            } else {
              start = this.count * this.girdActiveIndex;
              this.result = arr.slice(start, start + this.girdActiveIndex);
            }
          }, 300);
          //}, 3000000);
        }, loop_interval);
      }
    },

    //点击，分屏
    async clickGird(index, activeIndex) {
      this.girdActiveIndex = index;
      this.videoSelectedIndex = 0;
      this.activeIndex = activeIndex;
      if (index == 1) {
        this.girdArr[0].icon = require("assets/img/screen-ico-select-01.png");
        this.girdArr[1].icon = require("assets/img/screen-ico-04.png");
        this.girdArr[2].icon = require("assets/img/screen-ico-09.png");
        this.girdArr[3].icon = require("assets/img/screen-ico-16.png");
      } else if (index == 4) {
        this.girdArr[1].icon = require("assets/img/screen-ico-select-04.png");
        this.girdArr[0].icon = require("assets/img/screen-ico-01.png");
        this.girdArr[2].icon = require("assets/img/screen-ico-09.png");
        this.girdArr[3].icon = require("assets/img/screen-ico-16.png");
      } else if (index == 9) {
        this.girdArr[2].icon = require("assets/img/screen-ico-select-09.png");
        this.girdArr[0].icon = require("assets/img/screen-ico-01.png");
        this.girdArr[1].icon = require("assets/img/screen-ico-04.png");
        this.girdArr[3].icon = require("assets/img/screen-ico-16.png");
      } else if (index == 16) {
        this.girdArr[3].icon = require("assets/img/screen-ico-select-16.png");
        this.girdArr[0].icon = require("assets/img/screen-ico-01.png");
        this.girdArr[1].icon = require("assets/img/screen-ico-04.png");
        this.girdArr[2].icon = require("assets/img/screen-ico-09.png");
      }
      //   this.result=[]
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      await this.init();
      this.count = 0;
      // await this.fnInterval();
    },
    //点击video-wrap
    clickVideoItem(index) {
      this.videoSelectedIndex = index;
      this.selectIndex = index;
      var _videoSrcArr = this.videoSrcArr;
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>
<style scoped>
.wrap {
  height: calc(100vh - 60px);
  margin: -20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: #031229;
}
.task_name {
  color: #dee1e7;
  margin-left: 30px;
  font-size: 14px;
}
.content {
  position: relative;
  width: 100%;
  height: 100%;
}
.video-wrap {
  width: 100%;
  height: calc(100% - 60px);
  box-shadow: rgba(0, 0, 0, 0.55) 0px 2px 10px;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  overflow: hidden;
}
/* .video-wrap:after{
    content: "";
    width: 32%;
} */
.video-item {
  border: 1px solid #272d38;
  overflow: hidden;
}
.activeVideo {
  border: 1px solid #18d9cb;
  box-shadow: 0 2px 20px #4677d4;
}
/* 底部 */
.grid-wrap {
  position: absolute;
  bottom: 0;
  left: 0;
  margin-top: 10px;
  width: 100%;
  height: 50px;
  background: RGBA(64, 184, 250, 0.1);
  box-shadow: 0px -2px 10px #446ab6;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.grid-wrap ul {
  width: auto;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 15px;
}
.grid-wrap ul .grid-li {
  width: 36px;
  height: 36px;
  margin-right: 20px;
  border: 1px solid;
  /* color: #fff; */
}
.grid-wrap ul .grid-li img {
  width: 100%;
  height: 100%;
}

li {
  list-style: none;
}
.activeGrid {
  color: #561a91;
}
.video-item {
  margin: 10px 1%;
}
.video-item1 {
  width: 98%;
  height: 98%;
  display: block;
  margin-bottom: 10px;
  margin-top: 5px;
  border-radius: 20px;
}
.video-item4 {
  width: 48%;
  height: 48%;
  display: block;
  margin-bottom: 5px;
  margin-top: 5px;
  border-radius: 20px;
}
.video-item9 {
  width: 31.33%;
  height: 29%;
  display: block;
  border-radius: 20px;
}
.video-item16 {
  width: 23%;
  height: 19.5%;
  display: block;
  border-radius: 20px;
}
</style>
